package com.huaxin.common.message.mp3recorder.audio.receiver;

import android.util.Log;

import com.huaxin.common.message.mp3recorder.audio.NetConfig;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class AudioReceiver implements Runnable {
    String LOG = "AudioReceiver";
    int port = NetConfig.CLIENT_PORT;// 接收的端口
    DatagramSocket socket;
    DatagramPacket packet;
    boolean isRunning = false;

    private byte[] buffer = new byte[1024];

    /*
     * 开始接收数据
     */
    public void startRecieving() {
        new Thread(this).start();
    }

    /*
     * 停止接收数据
     */
    public void stopRecieving() {
        isRunning = false;
    }

    /*
     * 释放资源
     */
    private void release() {
        if (packet != null) {
            packet = null;
        }
        if (socket != null) {
            socket.close();
            socket = null;
        }
    }

    /*
     * init Player parameters
     */
    private boolean init() {
        if (socket == null) {
            try {
                socket = new DatagramSocket(port);
                packet = new DatagramPacket(buffer, buffer.length);
            } catch (SocketException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    public void run() {
        if (!init()) {
            Log.i(LOG, "Socket初始化失败");
            return;
        }
        // start player first
        AudioPlayer player = AudioPlayer.getInstance();
        player.startPlaying();

        isRunning = true;
        int n = 0;
        try {
            while (isRunning) {
                socket.receive(packet);
                player.addData(packet.getData(), packet.getLength());
                n++;
                Log.d("hebing", "recv : " + n);
            }

        } catch (IOException e) {
            Log.e(LOG, "RECIEVE ERROR!");
        }
        release();
        player.stopPlaying();
        Log.e(LOG, "stop recieving");
    }
}
